import java.io.File;
import java.io.FileOutputStream;

/**
 * Algorithm for Item Outlier detection using a Percentage
 * @author Joost Huizinga
 *
 */
public class AIOP extends Scheduler implements Runnable {
	static double PERCENT = 0.005;
	
	int start;
	int stop;
	byte[] BLOCK;

	public AIOP(int start, int stop) {
		this.start = start;
		this.stop = stop;
	}

	void writeBlock() {
		String FILE_NAME = String.format("%s%07d.bin", BLOCK_PATH, start);		File out = new File(FILE_NAME);
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(out);
			fos.write(BLOCK);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("Done writing: " + FILE_NAME + " @ "
				+ this.getClass());
	}

	@Override
	public void run() {
		int ilen = USERB[0].ilen;
		BLOCK = new byte[(stop - start) * ilen];
		int[] top = new int[((int)Math.floor(1000990*PERCENT))];
		fill(top, Integer.MAX_VALUE);
		
		int minIndex = minIndex(top);
		for (int bUserID = start; bUserID < stop; bUserID++) {
			int[] Items = USERA[bUserID].items;
			for (int i = 0; i < ilen; i++) {
				if(ITEMA[Items[i]].ulen > top[minIndex]){
					top[minIndex]=ITEMA[Items[i]].ulen;
					minIndex = minIndex(top);
				}
			}
		}
		
		int c = 0;
		for (int bUserID = start; bUserID < stop; bUserID++) {
			int[] Items = USERA[bUserID].items;
			for (int i = 0; i < ilen; i++) {
				BLOCK[c * ilen + i] = predict(ITEMA[Items[i]], top[minIndex(top)]);
			}
			c++;
		}

		writeBlock();
	}
	
	int minIndex(int[] input){
		if(input == null){
			return -1;
		}
		
		int min=input[0];
		int result=0;
		
		for(int i=0; i<input.length; i++){
			if(input[i] < min){
				min =input[i];
				result = i;
			}
		}
		
		return result;
	}
	
	int[] fill(int[] input, int value){
		for(int i=0; i<input.length; i++){
			input[i]=value;
		}
		return input;
	}
	
	byte predict(Item item, int threshold){
		if(item.ulen >= threshold){
			return 1;
		} else {
			return 0;
		}
	}
}